package com.book.lizhi;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;

import android.app.Application;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.text.TextUtils;
import cn.waps.AdInfo;
import cn.waps.AppConnect;
import cn.waps.UpdatePointsNotifier;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.database.BitmapCache;
import com.book.lizhi.database.JsonCache;
import com.book.lizhi.model.BookModel;
import com.book.lizhi.model.BookshelfModel;
import com.book.lizhi.util.AppLog;
import com.book.lizhi.util.Util;

public class AppApplication extends Application {
	public static AppApplication instance;

	public RequestQueue requestQueue;
	public ImageLoader imageLoader;

	public BookModel currentBookModel;
	public List<BookshelfModel> bookshelfModels = new ArrayList<BookshelfModel>();
	public List<String> bookshelfIDs = new ArrayList<String>();

	public List<BookModel> cacheBookModels;

	public AdInfo adInfo;

	public int points = 0;

	public boolean isCheck = true;

	public JsonCache jsonCache;

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;

		requestQueue = Volley.newRequestQueue(this);
		imageLoader = new ImageLoader(requestQueue, new BitmapCache());
		jsonCache = new JsonCache();

		AppConnect.getInstance(this).getPoints(new UpdatePointsNotifier() {

			@Override
			public void getUpdatePointsFailed(String arg0) {

			}

			@Override
			public void getUpdatePoints(String arg0, int arg1) {
				AppLog.e(arg0, "Points:" + arg1);
				points = arg1;
			}
		});

		AppConnect.getInstance(this).initPopAd(this);

		new Thread(new Runnable() {
			public void run() {
				try {
					String userId = Util.getStringBySharePreference(Constants.USER_ID);
					if (TextUtils.isEmpty(userId)) {
						userId = UUID.randomUUID().toString();
						userId = userId.replaceAll("-", "");
						String url = "https://fbook.firebaseio.com/users/" + userId + ".json";

						AndroidHttpClient httpClient = AndroidHttpClient.newInstance("android");
						HttpPut httpPost = new HttpPut(url);
						JSONObject params = new JSONObject();
						params.put("id", userId);
						httpPost.setEntity(new StringEntity(params.toJSONString(), "utf-8"));
						HttpResponse response = httpClient.execute(httpPost);
						httpClient.close();
						if (response.getStatusLine().getStatusCode() == 200) {
							Util.saveDataBySharePreference(Constants.USER_ID, userId);
						}
					}
				} catch (UnsupportedEncodingException e) {
				} catch (IOException e) {
				}
			}
		}).start();

		new AsyncTask<Void, Integer, List<BookModel>>() {

			@Override
			protected List<BookModel> doInBackground(Void... params) {
				String lastUrl = Util.getStringBySharePreference(Constants.LAST_REQUEST_BOOK_URL);
				AppLog.e("lasturl:"+lastUrl);
				if (!TextUtils.isEmpty(lastUrl)) {
					String cacheStr = AppApplication.instance.jsonCache.getJsonStr(lastUrl);
					AppLog.e(cacheStr);
					if (!TextUtils.isEmpty(cacheStr)) {
						AppApplication.instance.cacheBookModels = parseResponse(cacheStr);
					}
				}
				return null;

			}

		}.execute();

	}

	private List<BookModel> parseResponse(String response) {
		List<BookModel> bookModels=JSON.parseArray(response, BookModel.class);
		
		for (int i=0;i<bookModels.size();i++) {
			BookModel bookModel=bookModels.get(i);
			if (AppApplication.instance.bookshelfIDs.contains(bookModel.id)) {
				bookModel.isOnBookshelf = true;
			}
		}
		return bookModels;
	}

}
